<script lang="ts">
export default {
  name: "OperateManualTaskEditDialog"
}
</script>

<!--
 * @Description: 编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" width="1000px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="100px">

      <el-form-item label="模板名称" prop="name">
        <el-input v-model="dataState.formData.name" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <el-form-item label="设备厂商" prop="manufacturer"  style="width: 980px;">
        <el-select v-model="dataState.formData.manufacturer" placeholder="请选择"  style="width: 380px;"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="dataState.formData.deviceType" placeholder="请选择"  style="width: 380px;"
                     @change="handleSelectDeviceType">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>


      <el-form-item label="子集名称" prop="subsetName"  style="width: 980px;">
        <el-select v-model="dataState.formData.subsetName" placeholder="请选择"  style="width: 380px;"
                   @change="handleSubsetNameType">
          <el-option
            v-for="item in dataState.subsetNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="操作模板" prop="templateName">
          <el-select v-model="dataState.formData.templateName" placeholder="请选择"  style="width: 380px;">
            <el-option
              v-for="item in dataState.templateNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>


      <el-form-item label="云端参数" prop="cloudApiParamJson">
        <el-input v-model="dataState.formData.cloudApiParamJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

      <el-form-item label="参数描述" prop="description">
        <el-input v-model="dataState.formData.description" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {isEmpty} from "@/utils/fieldutil";
import {listOption4List} from "@/api/option";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加模板',
  // 表单数据
  formData: {
    id: 0,
    compId: 0,
    deviceType: '',
    name: '',
    manufacturer: '',
    subsetName: '',
    templateType: '',
    templateName: '',
    templateParam: {} as any,
    cloudApiParamJson: '{}',
    extendParam: {} as any,
    description: '',
  },

  operateNameOptions: [] as OptionType[],
  operateModeOptions: [] as OptionType[],
  manufacturerOptions: [] as OptionType[],
  deviceTypeOptions: [] as OptionType[],
  subsetNameOptions: [] as OptionType[],
  templateNameOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    name: [{required: true, message: '不能为空', trigger: 'blur'}],
    templateName: [{required: true, message: '不能为空', trigger: 'blur'}],
    manufacturer: [{required: true, message: '不能为空', trigger: 'blur'}],
    deviceType: [{required: true, message: '不能为空', trigger: 'blur'}],
    subsetName: [{required: true, message: '不能为空', trigger: 'blur'}],
    cloudApiParamJson: [{required: true, message: '不能为空', trigger: 'blur'}],
  },
});

async function handleSelectManufacturer(value: any) {
  await listDeviceTypeOption(true);
  await listSubsetNameOption(true);
  await listTemplateNameOption(true);
}

async function handleSelectDeviceType(value: any) {
  await listSubsetNameOption(true);
  await listTemplateNameOption(true);
}

async function handleSubsetNameType(value: any) {
  await listTemplateNameOption(true);
}

async function listManufacturerOption(nextMode: boolean) {
  let params = [];
  params.push({field:'templateType',value:'operate-param'});
  await listOption4List("DeviceTemplateEntity", "manufacturer", params).then(({data}) => {
    dataState.manufacturerOptions = data;
    if (dataState.manufacturerOptions.length > 0 && dataState.formData.manufacturer == ''){
      dataState.formData.manufacturer = dataState.manufacturerOptions[0].value;
    }
  });
}

async function listDeviceTypeOption(nextMode: boolean) {
  if (nextMode) {
    dataState.deviceTypeOptions = [];
    dataState.formData.deviceType = '';
  }

  let params = [];
  params.push({field:'templateType',value:'operate-param'});
  params.push({field:'manufacturer',value:dataState.formData.manufacturer});
  await listOption4List("DeviceTemplateEntity", "deviceType", params).then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (dataState.deviceTypeOptions.length > 0  && dataState.formData.deviceType == ''){
      dataState.formData.deviceType = dataState.deviceTypeOptions[0].value;
    }
  });
}

async function listSubsetNameOption(nextMode: boolean) {
  if (nextMode) {
    dataState.subsetNameOptions = [];
    dataState.formData.subsetName = '';
  }

  let params = [];
  params.push({field:'templateType',value:'operate-param'});
  params.push({field:'manufacturer',value:dataState.formData.manufacturer});
  params.push({field:'deviceType',value:dataState.formData.deviceType});
  await listOption4List("DeviceTemplateEntity", "subsetName", params).then(({data}) => {
    dataState.subsetNameOptions = data;
    if (dataState.subsetNameOptions.length > 0  && dataState.formData.subsetName == ''){
      dataState.formData.subsetName = dataState.subsetNameOptions[0].value;
    }
  });
}

async function listTemplateNameOption(nextMode: boolean) {
  if (nextMode) {
    dataState.templateNameOptions = [];
    dataState.formData.templateName = '';
  }

  let params = [];
  params.push({field:'templateType',value:'operate-param'});
  params.push({field:'manufacturer',value:dataState.formData.manufacturer});
  params.push({field:'deviceType',value:dataState.formData.deviceType});
  params.push({field:'subsetName',value:dataState.formData.subsetName});
  await listOption4List("DeviceTemplateEntity", "templateName", params).then(({data}) => {
    dataState.templateNameOptions = data;
    if (dataState.templateNameOptions.length > 0  && dataState.formData.templateName == ''){
      dataState.formData.templateName = dataState.templateNameOptions[0].value;
    }
  });
}

/**
 * 取消
 */
function handleCancel() {
  //执行调用<operateTemplate-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

function verifyTaskParam(): boolean {
  if (isEmpty(dataState.formData.name)
    || isEmpty(dataState.formData.manufacturer)
    || isEmpty(dataState.formData.deviceType)
    || isEmpty(dataState.formData.subsetName)
    || isEmpty(dataState.formData.templateName)
    || isEmpty(dataState.formData.templateType)
    || isEmpty(dataState.formData.cloudApiParamJson)
  ){
    ElMessage.info('输入参数缺失：模板名称、设备厂商、设备类型、操作子集、操作模板');
    return false;
  }

  dataState.formData.cloudApiParamJson = dataState.formData.cloudApiParamJson.trim();
  if (!dataState.formData.cloudApiParamJson.startsWith('{') || !dataState.formData.cloudApiParamJson.endsWith('}')) {
    ElMessage.info('输入参数，不是一个JSON对象，格式应该为{}');
    return false;
  }

  dataState.formData.templateParam.operateParam = {} as any;
  dataState.formData.templateParam.operateParam.manufacturer = dataState.formData.manufacturer;
  dataState.formData.templateParam.operateParam.deviceType = dataState.formData.deviceType;
  dataState.formData.templateParam.operateParam.subsetName = dataState.formData.subsetName;
  dataState.formData.templateParam.operateParam.templateName = dataState.formData.templateName;
  dataState.formData.templateParam.operateParam.templateType = 'operate-param';

  dataState.formData.templateParam.cloudApiParam = JSON.parse(dataState.formData.cloudApiParamJson as string);

  dataState.formData.extendParam.description = dataState.formData.description;

  return true;
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (!verifyTaskParam()) {
    return;
  }

  if (dataState.type === 'create') {
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    emit('update', dataState.formData);
  }
}

async function initEditData(type: string, entity: any) {
  dataState.formData.compId = entity.compId;

  dataState.formData.name = entity.templateName;

  if (!isEmpty(dataState.formData.name)){
    // 检查：是否为格式化的参数
    if (isEmpty(entity.templateParam.operateParam) || isEmpty(entity.templateParam.cloudApiParam)){
      return;
    }

    dataState.formData.id = entity.id as number;
    dataState.formData.manufacturer = entity.templateParam.operateParam.manufacturer;
    dataState.formData.deviceType = entity.templateParam.operateParam.deviceType;
    dataState.formData.subsetName = entity.templateParam.operateParam.subsetName;
    dataState.formData.templateName = entity.templateParam.operateParam.templateName;
    dataState.formData.templateType = entity.templateParam.operateParam.templateType;

    dataState.formData.cloudApiParamJson = JSON.stringify(entity.templateParam.cloudApiParam, null, 5);

    dataState.formData.extendParam = entity.extendParam;
    dataState.formData.description = entity.extendParam.description;

    listManufacturerOption(false);
    listDeviceTypeOption(false);
    listSubsetNameOption(false);
    listTemplateNameOption(false);
  } else {
    dataState.formData.templateName = '';
    dataState.formData.templateParam = {};
    dataState.formData.extendParam = {};
    dataState.formData.description = '';

    dataState.formData.manufacturer = '';
    dataState.formData.deviceType = '';
    dataState.formData.subsetName = '';
    dataState.formData.templateName = '';
    dataState.formData.templateType = 'operate-param';

    dataState.formData.templateParam.cloudApiParam = {};
    dataState.formData.templateParam.cloudApiParam.paraKey = 'cloud id 1';
    dataState.formData.templateParam.cloudApiParam.dataKey = 'id';
    dataState.formData.templateParam.cloudApiParam.dataType = 'int';
    dataState.formData.cloudApiParamJson = JSON.stringify(dataState.formData.templateParam.cloudApiParam, null, 5);

    dataState.formData.extendParam = {};
    dataState.formData.extendParam.description = '';
    dataState.formData.description = dataState.formData.extendParam.description;

    await listManufacturerOption(false);
    await listDeviceTypeOption(false);
    await listSubsetNameOption(false);
    await listTemplateNameOption(false);
  }

  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    dataState.formData.id = 0;

    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    dataState.formData.id = entity.id as number;
    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
});

</script>
